import logging

from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from utils.captcha.captcha import captcha
from .constants import IMAGE_CODE_REDIS_EXPIRES


class ImageCode(View):
    """
    获取图片验证码，存储再redis数据库中，返回验证码到前端
    """
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        conn_redis = get_redis_connection(alias='verify_codes')
        img_key = 'img_{}'.format(image_code_id).encode('utf-8')
        conn_redis.setex(img_key, IMAGE_CODE_REDIS_EXPIRES, text)
        logging.info('图片验证码：{}'.format(text))

        return HttpResponse(content=image, content_type='images/jpg')






















